import BusinessConstant from '@/constant/BusinessConstant';
import { useEffect, useMemo } from 'react';
import userStore from '@/stores/UserStore';
import authStore from '@/stores/AuthStore';
import chatStore from '@/stores/ChatStore';
import AuthConstant from '@/constant/AuthConstant';
import ChatBusiness from '@/business/ChatBusiness';
import { ChatEntity } from '@/entities/ChatEntity';
import { eventCenter } from '@tarojs/runtime';
import EventConstant from '@/constant/EventConstant';

export default function useChat() {
  const { user } = userStore;
  const { identity } = authStore;
  const {
    setChatSender,
    setChatSessionList,
    chatSessionList,
    setSenderId,
    setChatSessionLastOneMessageList,
    clearChatMessageList,
    senderId,
  } = chatStore;

  /**
   * 获取每个会话的最新一条消息
   */
  const getChatSessionLastOneMessage = async () => {
    const chatSessionLastOneMessageList: any =
      await ChatBusiness.getChatSessionLastOneMessageList(chatStore.senderId);
    setChatSessionLastOneMessageList(chatSessionLastOneMessageList);
  };

  /**
   * 获取会话列表
   */
  const getChatSessionList = async () => {
    if (chatStore.senderId) {
      // 获取会话信息
      const chatSession: any = await ChatBusiness.getChatSession(
        chatStore.senderId
      );
      if (chatSession?.length) {
        await getChatSessionLastOneMessage();
        setChatSessionList(chatSession);
      }
    }
  };
  /**
   * 初始化会话列表
   */
  const useInitChatSessionList = async () => {
    /**
     * 设置chat的sender id
     */
    const setChatSenderId = () => {
      if (identity === AuthConstant.LANDLORD) {
        setSenderId(`${BusinessConstant.SIGN_LANDLORD},${user.id}`);
      } else if (identity === AuthConstant.TENANT) {
        setSenderId(`${BusinessConstant.SIGN_TENANT},${user.id}`);
      }
    };

    useEffect(() => {
      if (user?.id) {
        // 设置chat里面的sender信息
        setChatSender(user);
        // 设置chat里面的senderId
        setChatSenderId();
      }
    }, [user]);

    useEffect(() => {
      getChatSessionList();
    }, [chatStore.senderId]);
  };

  /**
   * chat中的消息数量（未读的）
   */
  const chatMessageUnreadNum = useMemo(() => {
    // 有未读消息的 session
    const haveUnreadSessionList = chatSessionList?.filter(
      (session: ChatEntity.IChatSession) => session.unread !== 0
    );
    let unreadMessage = 0;
    haveUnreadSessionList?.forEach((session: ChatEntity.IChatSession) => {
      unreadMessage += session.unread;
    });
    return unreadMessage;
  }, [chatSessionList]);

  /**
   * 离开聊天会话（chatMessage -> chatSession）
   */
  const useLeaveChatSession = () => {
    useEffect(() => {
      // 从 聊天信息页 返回 会话页 需要重新获取 session 对话列表
      eventCenter.on(
        EventConstant.CHAT_MESSAGE_BACK,
        async (currentChatSession) => {
          if (!currentChatSession) return;
          const { id, senderId, receiverId } = currentChatSession;
          await ChatBusiness.leaveChatSession({
            sessionId: id!,
            senderId: senderId!,
            receiverId: receiverId!,
          });
          clearChatMessageList();
          // 重新获取 session 对话列表
          await getChatSessionList();
        }
      );

      return () => {
        eventCenter.off(EventConstant.CHAT_MESSAGE_BACK);
      };
    }, []);

    useEffect(() => {
      if (!senderId) return;
      // 清除当前sender的获取消息的游标
      ChatBusiness.clearSenderSessionCursor(senderId);
    }, [senderId]);
  };

  return {
    useInitChatSessionList,
    chatMessageUnreadNum,
    getChatSessionLastOneMessage,
    getChatSessionList,
    useLeaveChatSession,
  };
}
